package fr.enseirb.mycub.json.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;

import fr.enseirb.mycub.db.BikeDBHelper;
import fr.enseirb.mycub.db.DBAdapter;
import fr.enseirb.mycub.db.structure.bike.BikeStationDAO;
import fr.enseirb.mycub.json.JSONHandler;
import fr.enseirb.mycub.task.GetJSONAsyncTask;
import fr.enseirb.mycub.utils.Constants;

import android.content.Context;
import android.database.sqlite.SQLiteException;
import android.util.Log;

public class BikeStationJSONHandler extends JSONHandler{

	public static final String STATIONS = "stations";

	public BikeStationJSONHandler(Context context){
		super(context);
		this.preference_key_last_update_date = "BikeStationJSONHandler_last_update_date";
		this.preference_key_interval_adress = "BikeStationJSONHandler_interval_adress";
		this.preference_key_interval_between_update = "BikeStationJSONHandler_interval_between_update";

		this.preference_key_interval_between_update_default = 180000;
	}

	@Override
	public boolean updateLocalDatabase(String json) {
		Log.i("BikeJSONShort", "update local db :");
		Log.i("BikeJSONShort", json);
		boolean success = false;
		DBAdapter dbAdapter = DBAdapter.getInstance(context);
		try {
			Gson gson = new GsonBuilder().create();
			JsonResponse dao = gson.fromJson(json, JsonResponse.class);
			if (dao != null) {
				Log.i("BikeJSONShort", "stations :"+dao.stations.size());
				
				success = !BikeDBHelper.syncBikeStations(dbAdapter.getDB(),dao.stations);
				if (!success) {
					// Need Update
					fullUpdate();
				}
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}
		return success;
	}

	protected void fullUpdate() {
		Log.i("BikeJSON", "full update");
		new GetJSONAsyncTask(new BikeStationFullJSONHandler(context), Constants.SERVER_URL+"/inertness_webapp/bikefull").execute();
	}

	@Override
	protected void standardUpdate() {
		Log.i("BikeJSON", "update process");
		new GetJSONAsyncTask(this, Constants.SERVER_URL+"/inertness_webapp/bikeshort").execute();
	}

	private class JsonResponse{
		@SerializedName("stations")
		ArrayList<BikeStationDAO> stations;
	}
	
}
